<template>
    <Card class="renter-room-wrap card-body-grey renderRoom" style="border: 1px solid #e9eaec;">
        <!-- 房间信息 -->
        <p slot="title">
            <span style="font-weight:700">
                房间 - {{lease.room_name}}
            </span>
        </p>

        <!-- 租约详情 -->
        <Row type="flex" justify="space-between" :class="{'bb-dashed': lease.co_tenants.length}">
            <Col span="7" class="box">
                <div class="renter-room-text">房源编号：<span class="renter-room-text-content">{{lease.home_name}}</span></div>

                <div class="renter-room-text lh45">
                    所属门店：<span class="renter-room-text-content">{{lease.branch_name || '暂无'}}</span>
                </div>

                <div class="renter-room-text">
                    <span>房源地址：</span>
                    <span class="renter-room-text-content">
                        {{lease.city + lease.district}}{{lease.home_address}}
                    </span>
                </div>

                <div class="renter-room-text mar" v-if="lease.face_auth_devices && lease.face_auth_devices.length">
                    <span>授权门禁：</span>
                    <span class="renter-room-text-content">
                        <span v-for="(device, index) in lease.face_auth_devices" :key="index">{{device.description}}{{index + 1 === lease.face_auth_devices.length ? '' : ', '}}</span>
                    </span>
                </div>
            </Col>

            <Col span="7" class="box">
                <div class="renter-room-text clear-fix">
                    租期有效期：
                    <span class="renter-room-text-content">
                        {{new Date(lease.lease_range[0]).Format('yyyy/MM/dd HH:mm')}}
                        -
                        {{new Date(lease.lease_range[1]).Format('yyyy/MM/dd HH:mm')}}
                    </span>
                </div>

                <div class="renter-room-text clear-fix lh45">
                    <span>租约状态：
                        <span class="renter-room-text-content">{{lease | leaseStatus}}</span>
                    </span>
                </div>
            </Col>
            <Col span="3" class="box" v-if="lease.op_status != 1">
                <div class="frozen-text-box">
                    <span class="frozen-text">已冻结</span>
                </div>
            </Col>
            <Col span="7" class="box renter-box">
                <div class="renter-room-btns">
                    <!-- 此租客作为承租人 -->
                    <div v-if="!lease.tenant" class="renter-room-buttonWrap">
                        <Button type="ghost" size="default" @click="showContinue" v-pmis="30">续租</Button>
                        <Button style="margin-left:5px" type="ghost" size="default" @click="showFrozen" v-pmis="30" v-if="!hasFaceAccessPermission">{{lease.op_status==1?'冻结':'解冻'}}</Button>
                        <Button style="margin-left:5px" type="ghost" size="default" @click="showThrow" v-pmis="30">退租</Button>
                        <Button style="margin-left:5px" type="ghost" size="default" @click="addCorenter" v-if="isExpire">新增同租人</Button>
                        <Button type="ghost" size="default" @click="openGrantRecord(lease.tenant_id, roomDeviceIsExistList)" v-pmis="30" v-show="hasLock || hasAccessControll">授权记录</Button>
                    </div>
                    <!-- 此租客作为同租人 -->
                    <div v-if="lease.tenant">
                        <Button  type="ghost" size="default" @click="handleCoTenantLease(renterId, !!lease.face_auth_devices.length)" v-pmis="30">搬离房间</Button>
                    </div>
                </div>
            </Col>
        </Row>

        <!-- 作为同租人（只显示承租人） -->
        <Row type="flex" justify="space-between" style="padding:10px 20px;" v-if="lease.tenant">
            <div class="renter-role">
                <span style="font-weight:bold">承租人</span>：{{lease.tenant.name}} ({{lease.tenant.phone}})
            </div>
            <div >
                <Button  style="margin-right:10px" type="ghost" size="default" @click="turnToRenter(lease.tenant.id+'', lease.tenant.name)" v-pmis="29">查看详情</Button>
            </div>
        </Row>

        <!-- 作为承租人 (显示同租人) -->
        <Row type="flex" justify="space-between" style="padding:15px 20px 10px;" v-if="!lease.tenant" v-for="(item, index) in lease.co_tenants" :key="index">
            <div class="renter-role">
                <span style="font-weight:bold">同租人</span>：{{item.name}} ({{item.phone}})
            </div>
            <div >
                <Button  style="margin-right:10px" type="ghost" size="default" @click="handleCoTenantLease(item.co_tenant_lease.tenant_id, !!lease.face_auth_devices.length)" v-pmis="30">删除同租人</Button>
                <Button  style="margin-right:10px" type="ghost" size="default" @click="turnToRenter(item.co_tenant_lease.tenant_id+'', item.name)" v-pmis="29">查看详情</Button>
            </div>
        </Row>

        <!-- 添加同租人(只有此租客作为承租人时才展示) -->
        <Row v-if="!lease.tenant">
            <Row v-show="coRenterNumber" style="padding:0;margin-bottom:14px;padding:15px 20px 10px;" class="bt-dashed">
                <Col span="24">
                    <p style="font-weight:bold;margin-bottom:10px">添加同租人:</p>
                    <renterCo
                    v-for="(item,index) in corentersData"
                    :corIndex="index"
                    :key="index"
                    :faceDevices="lease.face_auth_devices"
                    :homeId="lease.home_id"
                    :isRenterDetail="true"
                    :leaseId="lease.id"
                    :tenantId="renterId"
                    :roomId="lease.room_id"
                    :leaseRange="lease.lease_range"
                    @removeCorenterData="removeCorenterData"
                    @addCoTenants="addCoTenants">
                    </renterCo>
                </Col>
            </Row>
        </Row>

        <!-- 续租 -->
        <renterContinue
        :lease="lease"
        :hasFaceDeviceAndPermission="hasFaceDeviceAndPermission"
        v-if="isContinueVisible"
        @cancelContinue="cancelContinue"
        @continueSuccess="continueSuccess"
        :renterId="renterId">
        </renterContinue>

        <!-- 解冻 -->
        <renterFrozen
        :lease="lease"
        v-if="isFrozenVisible"
        @cancelContinue="cancelFrozen"
        @frozenSuccess="frozenSuccess"
        :renterId="renterId">
        </renterFrozen>

        <!-- 退租 -->
        <renterOut
        :lease="lease"
        :faceAccess="hasFaceDeviceAndPermission"
        :renterId="renterId"
        v-if="isThrowVisible"
        @cancelOut="cancelOut"
        @outSuccess="outSuccess">
        </renterOut>

    </Card>
</template>

<script>
// import util from '@/libs/util';
import renterCo from './renterCo.vue'
import renterContinue from './renterContinue.vue'
import renterFrozen from './renterFrozen.vue'
import renterOut from './renterOut.vue'
import { http, api } from '@/libs/http'
import { DeviceTypeEnum } from '@/libs/const'
import { mapState } from 'vuex'
export default {
  name: 'renterRoom',
  props: {
    lease: {
      // 租约对象包含租客和同租人
      type: Object,
      required: true
    },
    renterId: {
      required: true // 租客id
    }
  },
  components: {
    renterCo,
    renterContinue,
    renterFrozen,
    renterOut
  },

  computed: {
    ...mapState({
      hasFaceAccessPermission: state => state.user.hasFaceAccessPermission
    }),

    // 房间是否有这个设备列表.第一个是是否含有锁，第二个是否含有m3门禁
    roomDeviceIsExistList () {
      return [this.hasLock, this.hasAccessControll]
    },

    hasFaceDeviceAndPermission () {
      return this.hasFaceAccessPermission && this.lease && this.lease.face_auth_devices && this.lease.face_auth_devices.length > 0
    },

    /**
        * 是否过期
        */
    isExpire () {
      if (this.lease && this.lease.lease_range) {
        const endTime = this.lease.lease_range[1]

        return !(new Date().valueOf() > new Date(endTime).valueOf())
      } else {
        return false
      }
    }
  },

  mounted () {
    this.init()
  },

  data () {
    return {
      hasAccessControll: false, // 是否有门禁设备
      isContinueVisible: false,
      isFrozenVisible: false,
      isThrowVisible: false,
      coRenters: 0,
      hasLock: false, // 是否有门锁
      coRenterNumber: 0, // 新增有效同租人数量
      corentersData: [] // 新增同租人数组
    }
  },
  filters: {
    leaseStatus (lease) {
      const start = new Date(lease.lease_range[0])
      const end = new Date(lease.lease_range[1])
      const frozenStatus = lease.op_status
      const now = Date.now()
      if (now < start) {
        return '未生效'
      }
      if (now > end) {
        return '已过期'
      }
      return frozenStatus === 1 ? '已生效' : '已冻结'
    }
  },
  methods: {
    /**
         * 查看该租约是否有门锁（包含租约所在房间和公区所在房间是否含有门锁）
         */
    init () {
      const { room, public_room } = this.lease

      this.hasLock = this.roomHasLock(room) || this.roomHasLock(public_room)

      this.hasAccessControll = this.roomHasAccess(room) || this.roomHasAccess(public_room)
    },

    /**
        *  房间是否有门禁设备
        */
    roomHasAccess (room) {
      const { devices } = room

      return devices.some(value => {
        return value.device_type === DeviceTypeEnum.ACCESS_CONTROL
      })
    },

    /**
         * 房间是否包含门锁，如果包含返回true，否则返回false
         * @param {Object} room
         * @return {Boolean}
         */
    roomHasLock (room) {
      const { devices } = room

      return devices.some(value => {
        return value.device_type === DeviceTypeEnum.LOCK
      })
    },

    /**
         * 打开授权记录
         */
    openGrantRecord (tenantId, roomDeviceIsExistList) {
      this.$emit('openGrantRecord', String(this.lease.id), this.lease.room_name, tenantId, roomDeviceIsExistList)
    },

    removeCorenterData () {
      // 隐藏新增同租人列表框
      this.coRenterNumber--
    },

    refresh () {
      this.$emit('refresh')
    },

    /**
         * 同租人添加成功后，在前端添加相关同租人数据
         * @param {Array} flag 添加同租人成功后传递同租人数据 arr[0]，arr[1]，arr[2]分别为id，name和phone
         */
    addCoTenants (flag) {
      let obj = {
        name: flag[1],
        phone: flag[2],
        co_tenant_lease: {
          tenant_id: flag[0]
        }
      }
      this.lease.co_tenants.push(obj)
      this.refresh()
    },

    /**
         *
         * 删除同租人，并且刷新租客信息
         */
    async moveAway (co_tenant_id, needDelFaceAuth) {
      if (needDelFaceAuth) {
        await this.deleteFaceAuth(co_tenant_id)
      }

      let params = { lease_id: this.lease.id }

      this.deleteFingerRecord(co_tenant_id)

      http.request(this, api.tenant_co_del, [co_tenant_id], params, (res, err) => {
        this.$Modal.remove()
        if (err) return

        this.$Message.success('删除同租人成功')
        this.$emit('refresh')
        this.$store.commit('refresh_renter', Math.random())
      })
    },

    /**
         * 删除同租人同时也删除同租人的指纹记录
         * @param {Number} co_tenant_id 同租人id
         */
    deleteFingerRecord (co_tenant_id) {
      http.request(this, api.tenant_co_finger_del, [this.lease.id, co_tenant_id], null, (res, err) => {
        if (err) {

        }
      })
    },

    /**
         * 传递参数打开新的参数详情页
         * @param {String} id
         * @param {String} name
         */
    turnToRenter (id, name) {
      this.$emit('openNewTab', id, name)
    },

    setEditMode () {},
    addCorenter () {
      this.corentersData.push({})
      this.coRenterNumber++
    },
    showContinue () {
      const { lease_range } = this.lease
      const isExpired = new Date(lease_range[1]).getTime() < Date.now()
      if (this.hasFaceAccessPermission && isExpired) {
        this.$Message.info('已过期租约不能修改，请重新入住。')
      } else {
        this.isContinueVisible = true
      }
    },
    cancelContinue () {
      this.isContinueVisible = false
    },
    cancelFrozen () {
      this.isFrozenVisible = false
    },
    continueSuccess () {
      this.isContinueVisible = false
      this.refresh()
    },
    showFrozen () {
      this.isFrozenVisible = true
    },
    showThrow () {
      this.isThrowVisible = true
    },
    cancelOut () {
      this.isThrowVisible = false
    },
    outSuccess () {
      this.isThrowVisible = false
      this.refresh()
    },
    frozenSuccess () {
      this.isFrozenVisible = false
      this.refresh()
    },
    handleCoTenantLease (tenantId, needDelFaceAuth) {
      this.$Modal.confirm({
        loading: true,
        title: '确认删除同租人?',
        content: '同租人搬离房间不会删除相关授权(门禁除外)，请在授权列表中处理',
        onOk: () => {
          this.moveAway(tenantId, needDelFaceAuth)
        }
      })
    },

    /**
        * 删除人脸授权
        */
    async deleteFaceAuth (tenantId) {
      try {
        await http.fetch(this, api.renter_face_auth_delete, [this.lease.id, tenantId])

        this.$Message.success('同租人门禁授权删除成功!')
      } catch (error) {
        console.log('error', error)
      }
    }
  }
}
</script>

<style lang="less">
.bb-dashed {
    border-bottom: 1px dashed #bbbec4;
}
.bt-dashed {
    border-top: 1px dashed #bbbec4;
}
.frozen-text-box {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}
.frozen-text {
    font-size: 30px;
    color: #ccc;
    font-style: italic;
}
.lh45 {
    height: 36px;
    line-height: 36px;
}
.renter-role {
    font-weight: 400;
    display: flex;
    align-items: center;
}
button {
    cursor: pointer;
}
.renter-room {
    &-buttonWrap {
        text-align: left;
        > button {
            margin-bottom: 10px;
        }
    }
    &-wrap {
        margin-top: 15px;
        background: #efeff1;
        padding-bottom: 10px;
    }
    &-text {
        margin-bottom: 10px;
        font-weight: 400;
    }
    &-text-content {
        margin-bottom: 10px;
        font-weight: normal;
        font-size: 12px;
    }
    &-header {
        margin-bottom: 10px;
        padding: 10px;
    }
    &-btns {
        text-align: center;
        // padding: 50px 10px 0 0;
    }
    &-cell-label {
        text-align: right;
    }
    &-cell {
        margin-top: 10px;
    }
    &-co-wrap {
        padding: 0 20px;
    }
}
.renter-room-wrap {
    padding-bottom: 0;
    border: 1px solid #e9eaec;
}
.renderRoom {
    .ivu-card-body {
        padding: 0!important;
    }
    .box {
        padding: 30px 10px;
        border-right: 1px dashed #e9eaec;
    }
}
.renter-box {
    display: flex;
    align-items: center;
}

.mar {
    margin-top: 20px;
}
</style>
